<template>
  <el-popover v-model="visible" :width="pics.length<7?80:96" placement="bottom" trigger="click">
    <el-container>
      <el-main>
        <div v-for="(pic,i) in pics" :key="pic.url" class="simg" @click.stop="onLogoClick(i)">
          <img :src="pic.url" width="50" height="50" />
        </div>
      </el-main>
    </el-container>
    <div slot="reference" class="solt">
      <img :src="logo_url"  width="50" height="50"/>
    </div>
  </el-popover>
</template>

<script>
import {findIndexByKeyValue} from '@/api/common';//按指定关键字找元素，返回第一个匹配成功的下标
export default {
  props: {
    value: { type: Number, default: 0 }, //图标的 ProductFile.ProductFileID
    pics: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  data() {
    return {
      file_id: 0,
      logo_url: "",
      visible: false
    };
  },
  created() {
    this.SetMyValue();
  },
  watch: {
    pics: function(nval) {
      this.SetMyValue();
    },
    value: function(nval) {
      this.SetMyValue();
    }
  },
  methods: {
    SetMyValue() {
      if (this.$props.pics.length == 0) return;
      let val = this.$props.value;
      if (val == 0) {
        this.logo_url = this.$props.pics[0].url;
      } else {
        this.logo_url = this.GetLogoUrl(val);
      }
    },
    onLogoClick(i) {
      this.logo_url = this.$props.pics[i].url;
      this.file_id = this.$props.pics[i].id;
      this.visible = false;
      this.$emit("change", this.file_id);//返回值
      setTimeout(() => {
        this.$emit("set");//可处理返回值
      }, 200); //延后至change处理完
    },
    //-----------------------------------------------------------
    GetLogoUrl(file_id) {
      let url = "";
      let pics = this.$props.pics;
      if (pics.length == 0) {
        url = pics[0].url;
      } else {
        let i = findIndexByKeyValue(pics, "id", file_id);
        if (i >= 0) {
          url = pics[i].url;
        } else {
          url = pics[0].url;
        }
      }
      return url;
    }    
  }
};
</script>

<style lang="scss" scoped>
.solt {
  cursor: pointer;
}
.simg {
  border: 1px solid white;
  margin-bottom: 1px;
}
.simg:hover {
  cursor: pointer;
  border: 1px solid red;
}
.el-container {
  max-height: 320px;
  .el-main {
    padding: 0;
  }
}
</style>

<style>
/* 全局才能修改el-popover的属性 */
.el-popover {
  min-width: 80px;
  padding: 3;
  border: 1px solid #dddddd;
}
</style>
